<template>
  <div class="workorder-selector">
    <el-dialog
      :title="title"
      v-model="visible"
      width="900px"  
      append-to-body
      @close="handleClose"
      destroy-on-close
    >
      <!-- 搜索条件 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
        <el-form-item label="工单编号" prop="orderCode">
          <el-input
            v-model="queryParams.orderCode"
            placeholder="请输入工单编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="queryParams.productId"
            placeholder="请选择产品"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择工单状态" clearable>
            <el-option
              v-for="dict in work_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格数据 -->
      <el-table 
        v-loading="loading" 
        :data="workorderList" 
        @row-click="handleRowClick"
        highlight-current-row
        :row-class-name="rowClassName"
        height="400px"
        border
      >
        <el-table-column label="工单ID" align="center" prop="orderId" width="80" />
        <el-table-column label="工单编号" align="center" prop="orderCode" width="100" />
        <el-table-column label="产品" align="center" prop="productName" width="120" />
        <el-table-column label="生产线" align="center" prop="lineName" width="120" />
        <el-table-column label="计划生产数量" align="center" prop="planQuantity" width="100" />
        <el-table-column label="完成数量" align="center" prop="finishedQuantity" width="100" />
        <el-table-column label="工单状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="work_order_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click.stop="selectWorkorder(scope.row)"
              :disabled="!isWorkorderSelectable(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        :pageSizes="[5, 10, 20, 30]"
        :small="true"
      />

      <!-- 添加工单关联的生产计划信息 -->
      <div v-if="selectedWorkorder" class="plan-info-container">
        <el-divider content-position="center">关联生产计划信息</el-divider>
        
        <el-descriptions :column="3" border v-if="relatedPlan">
          <el-descriptions-item label="计划编号">{{ relatedPlan.planCode || '-' }}</el-descriptions-item>
          <el-descriptions-item label="计划名称">{{ relatedPlan.planName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="计划数量">{{ relatedPlan.planQuantity || '-' }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ relatedPlan.startTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ relatedPlan.endTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <dict-tag :options="plan_status" :value="relatedPlan.status"/>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-alert
          v-else
          title="该工单未关联生产计划或无法获取计划信息"
          type="info"
          :closable="false"
          show-icon
          style="margin: 10px 0"
        />
      </div>
      
      <!-- 添加物料清单展示区域 -->
      <div v-if="selectedWorkorder && materialList.length > 0" class="material-list-container">
        <el-divider content-position="center">物料清单</el-divider>
        <el-table 
          :data="materialList" 
          border 
          height="240px"
          :header-cell-style="{background:'#f7f7f7'}"
        >
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="物料编码" prop="materialCode" width="120" align="center" />
          <el-table-column label="物料名称" prop="materialName" width="150" align="center" />
          <el-table-column label="规格型号" prop="specification" width="120" align="center" />
          <el-table-column label="数量" prop="quantity" width="80" align="center" />
          <el-table-column label="单位" prop="unit" width="80" align="center" />
          <el-table-column label="来源" prop="source" width="100" align="center" />
          <el-table-column label="备注" prop="remark" min-width="120" align="center" />
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button 
            type="primary" 
            @click="confirmSelection" 
            :disabled="!selectedWorkorder"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listWorkorder, listProduct, getWorkorder } from "@/api/pm/workorder";
import { getPlan } from "@/api/pm/plan"; // 导入获取计划API
import { ref, reactive, toRefs, getCurrentInstance, defineProps, defineEmits, watch } from 'vue';

const { proxy } = getCurrentInstance();
const { work_order_status, plan_status } = proxy.useDict('work_order_status', 'plan_status');

// 定义属性和事件
const props = defineProps({
  title: {
    type: String,
    default: '选择工单'
  },
  visible: {
    type: Boolean,
    default: false
  },
  filters: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'select']);

// 数据部分
const workorderList = ref([]);
const productOptions = ref([]); 
const loading = ref(false);
const visible = ref(false);
const total = ref(0);
const selectedWorkorder = ref(null);
const selectedRowIndex = ref(null);

// 新增关联计划和物料清单数据
const relatedPlan = ref(null);
const materialList = ref([]);
const planLoading = ref(false);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderCode: null,
    productId: null,
    status: null
  }
});

const { queryParams } = toRefs(data);

// 监听visible变化
watch(() => props.visible, (val) => {
  if (val) {
    // 当弹窗显示时初始化数据
    listProduct().then(response => {
      productOptions.value = response.data;
    });
    getList();
  }
  visible.value = val;
});

// 监听内部visible变化
watch(() => visible.value, (val) => {
  emit('update:visible', val);
});

// 查询工单列表
function getList() {
  loading.value = true;
  // 合并基本查询参数与传入的过滤条件
  const params = {
    ...queryParams.value,
    ...props.filters,
  };
  
  listWorkorder(params).then(response => {
    workorderList.value = response.rows || [];
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 判断工单是否可选
function isWorkorderSelectable(workorder) {
  // 全部允许选择，通过外部传入的过滤条件控制显示哪些工单
  return true;
}

// 行样式
function rowClassName({row, rowIndex}) {
  let classNames = '';
  
  // 选中行高亮
  if (selectedRowIndex.value === rowIndex) {
    classNames += 'row-selected ';
  }
  
  return classNames;
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 行点击事件
function handleRowClick(row, column, event) {
  // 移除状态判断，所有行都可点击
  selectedWorkorder.value = row;
  selectedRowIndex.value = workorderList.value.findIndex(item => item.orderId === row.orderId);
  
  // 加载工单关联的计划和物料清单
  loadWorkorderRelatedInfo(row.orderId);
}

// 加载工单关联的计划和物料清单
function loadWorkorderRelatedInfo(orderId) {
  planLoading.value = true;
  materialList.value = [];
  relatedPlan.value = null;
  
  // 获取工单详情
  getWorkorder(orderId).then(response => {
    if (response.code === 200 && response.data) {
      const workorderData = response.data;
      
      // 如果有计划ID，获取计划详情
      if (workorderData.planId) {
        // 记录工单自身的物料清单（如果有）
        let workorderMaterials = [];
        if (workorderData.materialList && workorderData.materialList.length > 0) {
          workorderMaterials = workorderData.materialList.map(item => {
            return {
              ...item,
              source: '工单'
            };
          });
        }
        
        // 获取关联的计划详情
        getPlan(workorderData.planId).then(planResponse => {
          if (planResponse.code === 200 && planResponse.data) {
            // 设置关联计划
            relatedPlan.value = planResponse.data;
            
            // 获取计划的物料清单
            let planMaterials = [];
            if (planResponse.data.bomMaterials && planResponse.data.bomMaterials.length > 0) {
              planMaterials = planResponse.data.bomMaterials.map(item => {
                return {
                  ...item,
                  source: '计划'
                };
              });
            }
            
            // 合并工单和计划的物料清单
            materialList.value = [...planMaterials];
            
            // 如果计划没有物料但工单有，则使用工单的物料清单
            if (materialList.value.length === 0 && workorderMaterials.length > 0) {
              materialList.value = workorderMaterials;
            }
          }
          planLoading.value = false;
        }).catch(error => {
          console.error("获取计划信息失败:", error);
          // 如果获取计划失败但工单有物料，使用工单物料
          if (workorderMaterials.length > 0) {
            materialList.value = workorderMaterials;
          }
          planLoading.value = false;
        });
      } else {
        // 没有关联计划，但可能有自己的物料清单
        if (workorderData.materialList && workorderData.materialList.length > 0) {
          materialList.value = workorderData.materialList.map(item => {
            return {
              ...item,
              source: '工单'
            };
          });
        }
        planLoading.value = false;
      }
    } else {
      planLoading.value = false;
    }
  }).catch(error => {
    console.error("获取工单详情失败:", error);
    planLoading.value = false;
  });
}

// 选择工单
function selectWorkorder(row) {
  selectedWorkorder.value = row;
  selectedRowIndex.value = workorderList.value.findIndex(item => item.orderId === row.orderId);
  loadWorkorderRelatedInfo(row.orderId);
}

// 确认选择
function confirmSelection() {
  if (selectedWorkorder.value) {
    emit('select', {
      workorder: selectedWorkorder.value,
      plan: relatedPlan.value,
      materialList: materialList.value
    });
    handleClose();
  }
}

// 关闭对话框
function handleClose() {
  emit('update:visible', false);
  selectedWorkorder.value = null;
  selectedRowIndex.value = null;
  relatedPlan.value = null;
  materialList.value = [];
}

// 打开方法，由父组件调用
function open() {
  visible.value = true;
  reset();
  // 初始化数据
  listProduct().then(response => {
    productOptions.value = response.data;
  });
  
  getList();
}

// 重置方法
function reset() {
  queryParams.value.orderCode = null;
  queryParams.value.productId = null;
  queryParams.value.status = null;
  queryParams.value.pageNum = 1;
  selectedWorkorder.value = null;
  selectedRowIndex.value = null;
}

// 添加设置过滤条件的方法
function setFilters(filters) {
  // 合并过滤条件
  props.filters = {
    ...props.filters,
    ...filters
  };
  
  // 刷新列表
  if (visible.value) {
    getList();
  }
}

// 对外暴露方法
defineExpose({
  open,
  setFilters
});
</script>

<style scoped>
.workorder-selector .row-selected {
  background-color: #f0f9eb !important;
}

.workorder-selector .row-disabled {
  background-color: #f9f9f9 !important;
  color: #999 !important;
  cursor: not-allowed !important;
}

.workorder-selector .el-table {
  margin-top: 10px;
  margin-bottom: 10px;
}

.workorder-selector .pagination-container {
  margin-top: 10px;
}

/* 新增样式 */
.plan-info-container {
  margin-top: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.material-list-container {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f8f9;
  border-radius: 4px;
}
</style> 